﻿using System;
using System.Collections.Generic;
using System.Globalization;
using Kugar.Core.BaseStruct;
using Kugar.Core.Web;
using Kugar.Tool.Web.RequestFieldValidation.Resources;
using Microsoft.Extensions.Localization;

namespace Kugar.Tool.Web.RequestFieldValidation
{
    public interface IRule
    {
        ResultReturn Validate(IRequestField field);

        string BuildErrorMessage(IRequestField field);
    }

    public class EmptyStringLocalizer<T> : IStringLocalizer<T>
    {
        public IEnumerable<LocalizedString> GetAllStrings(bool includeParentCultures)
        {
            return Array.Empty<LocalizedString>();
        }

        public IStringLocalizer WithCulture(CultureInfo culture)
        {
            return this;
        }

        public LocalizedString this[string name] => new LocalizedString(name,"",true);

        public LocalizedString this[string name, params object[] arguments] => new LocalizedString(name, "", true);
    }

    public abstract class RuleBase : IRule
    {
        private string _errorMsg = null;

        protected RuleBase(string errorMsg, IStringLocalizer<ValidatieError> localizer=null)
        {
            if (localizer==null)
            {
                localizer =
                    (IStringLocalizer<ValidatieError>) HttpContext.Current.RequestServices.GetService(
                        typeof(IStringLocalizer<ValidatieError>));
            }

            if (localizer==null)
            {
                localizer = new EmptyStringLocalizer<ValidatieError>();
            }

            Localizer = localizer;

            //_errorMsg=new Lazy<string>(BuildErrorMessage);
            _errorMsg = errorMsg;
        }

        protected IStringLocalizer Localizer { get; }

        public virtual ResultReturn Validate(IRequestField field)
        {
            if (ValidateField(field))
            {
                return SuccessResultReturn.Default;
            }
            else
            {
                var error = _errorMsg;

                if (string.IsNullOrEmpty(_errorMsg))
                {
                    error = BuildErrorMessage(field);
                }
                
                return new FailResultReturn(error);
            }
        }



        public string BuildErrorMessage(IRequestField field)
        {
            if (string.IsNullOrWhiteSpace(_errorMsg))
            {
                return BuildDefaultErrorMessage(field);
            }
            else
            {
                return _errorMsg;
            }
        }

        /// <summary>
        /// 各个规则,构建默认的错误提示
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        protected abstract string BuildDefaultErrorMessage(IRequestField field);

        protected abstract bool ValidateField(IRequestField field);
    }


}